package cn.cxyxj.sso.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;

@Configuration
@Order(1)
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.inMemoryAuthentication()
                .withUser("cxyxj")
                .password(new BCryptPasswordEncoder().encode("123"))
                .roles("admin")
                .and()
                .withUser("dev")
                .password(new BCryptPasswordEncoder().encode("123"))
                .roles("dev");
    }

    @Bean
    PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }

    @Override

    public void configure(WebSecurity web) throws Exception {

        web.ignoring().antMatchers("/favicon.ico");

    }

    @Override
    public void configure(HttpSecurity http) throws Exception {
        http.requestMatchers().antMatchers("/oauth/authorize", "/login")
                .and()
                .authorizeRequests()
                .antMatchers("/user/get-user-info", "/user/get-current-user").hasAnyRole("dev", "admin")
                .antMatchers("/user/**").hasRole("admin")
                .antMatchers("/favicon.ico", "/error").permitAll()
                .anyRequest().authenticated()
                .and().formLogin()
                .successHandler(new MyAuthenticationSuccessHandler()).permitAll();

        http.csrf().disable();
    }

}
